<template>
  <div style="div">
    <el-upload
      v-if="type=='file'"
      :action="datas?http2:http"
      :data="datas"
      ref="upload"
      :on-success="handleAvatarSuccess"
      :on-exceed="handleExceed"
      accept=".jpg, .jpeg, .png, .pdf, .JPG, .JPEG, .PBG, .PDF"
      :on-preview="handlePictureCardPreview"
      :on-change="changeUpload"
      :before-upload="beforeAvatarUpload"
      :on-remove="handleRemove"
      :headers="headers"
      :limit="fileNum"
      :file-list="fileList"
      :disabled="disabled"
      :class="{hide:hideUpload}"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-upload
      v-else
      :action="http"
      list-type="picture-card"
      ref="upload"
      accept="image/gif, image/jpeg, image/jpg, image/png"
      :on-preview="handlePictureCardPreview"
      :on-change="changeUpload"
      :before-upload="beforeAvatarUpload"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      :headers="headers"
      :limit="fileNum"
      :file-list="fileList"
      :class="{hide:hideUpload}"
    >
      <i class="el-icon-plus"></i>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="该文件无法展示" />
    </el-dialog>
  </div>
</template>
<script>
import { getupload } from "@/api/policy";
import $ from "jquery";
import service from "@/utils/request";
export default {
  data() {
    return {
      http: service.defaults.baseURL + "/upload",
      http2: service.defaults.baseURL + "/uploadHospital",
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      imgFlag: [],
      issure: true
      // imgUploadFlag:true,
    };
  },
  props: {
    datas: {},
    fileList: Array,
    fileNum: Number,
    width: "",
    height: "",
    type: "",
    accept: "",
    disabled: false
  },
  mounted() {},
  computed: {
    headers() {
      return {
        Authorization: "Bearer " + localStorage.getItem("token") // 直接从本地获取token就行
      };
    }
  },

  methods: {
    handleAvatarSuccess(res, file, fileList) {
      //response这个
      this.$message({
        message: res.msg,
        type: "warning"
      });
      //    this.$message.error(res.msg);

      for (let i = 0; i < this.imgFlag.length; i++) {
        if (this.imgFlag[i].response) {
          if (this.imgFlag[i].response.code != 0) {
            console.log(1111);

            console.log(this.imgFlag);
            this.imgFlag.splice(i, 1);
          }
        }
      }
    },
    handleExceed() {
      this.$message.warning(`当前限制了文件数：` + this.fileNum);
    },
    getLength(fileList) {
      this.hideUpload = fileList.length >= this.fileNum;
    },
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.fileNum;
    },
    handlePictureCardPreview(file) {
      console.log(file);
      this.dialogImageUrl = file.url
        ? file.url
        : localStorage.getItem("imgUrlPrefix") + file.response.data;
      if (this.dialogImageUrl.indexOf(".pdf") == -1) {
        this.dialogVisible = true;
      } else {
        window.open(this.dialogImageUrl);
      }
    },
    changeUpload(file, fileList) {
      console.log(file.response);
      this.hideUpload = fileList.length >= this.fileNum;
      // console.log(fileList);

      // console.log(fileList);
      this.imgFlag = fileList;
    },
    beforeAvatarUpload(file) {
      // console.log(this.accept);
      // console.log(this.datas)
      // console.log(this.$refs)
      if (this.accept !== undefined) {
        if (this.accept.indexOf(file.name.split(".")[1]) == -1) {
          //不在接收范围内
          this.$message.error("文件类型不对");
          return false;
        }
      }

      if (this.width) {
        var that = this;
        const isSize = new Promise(function(resolve, reject) {
          // let width = that.width;
          // let height = that.height;
          let _URL = window.URL || window.webkitURL;
          let image = new Image();
          console.log(image);
          console.dir(image.width);
          image.onload = function() {
            let valid =
              image.width >= that.width && image.height >= that.height;
            console.log("width", that.width);
            console.log("height", that.height);
            console.log("valid", valid);
            console.log("image.width", image.width);
            console.log("image.height", image.height);
            valid ? resolve() : reject();
          };
          image.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          err => {
            console.log("err", err);
            if (!err) {
              // this.$message.error("图片尺寸限制最小为1080 x 1920");
              this.$message.error(
                "图片尺寸限制最小为" + that.width + "*" + that.height
              );

              return Promise.reject();
            }
            console.log("width", that.width);
            console.log("height", that.height);
            // console.log(that.width);
            // let image = new Image();
            // let valid =
            //   image.width >= that.width && image.height >= that.height;

            // // console.log("valid", valid);
            console.log("image.width", image.width);
            // if (valid) {
            //   return Promise.reject();
            // } else {
            //   this.$message.error("图片尺寸限制最小为1080 x 1920");
            // }
            // this.$message.error("图片尺寸限制最小为1080 x 1920");
            // return Promise.reject();
          }
        );

        return isSize;
      }
    },
    //字符串截取
    getCaption(obj) {
      console.log(obj);
      var index = obj.lastIndexOf(".com/");
      obj = obj.substring(index + 5, obj.length);
      return obj;
    },
    submitUpload() {
      let oldList = [];
      let newList = [];
      for (var i = 0; i < this.$refs.upload.uploadFiles.length; i++) {
        if (this.$refs.upload.uploadFiles[i].name) {
          if (this.$refs.upload.uploadFiles[i].response) {
            newList.push(this.$refs.upload.uploadFiles[i].response.data);
          } else {
            newList.push(this.$refs.upload.uploadFiles[i].name);
          }
        } else {
          oldList.push(this.getCaption(this.$refs.upload.uploadFiles[i].url));
        }
      }
      this.imgFlag = [...oldList, ...newList];
      return this.imgFlag;
    }
  }
};
</script>
<style scoped>
.div,
.div > div {
  display: inline;
}
</style>
